import React, { useEffect, useRef, useState } from 'react';
import {
  Button,
  Form,
  Input,
  InputNumber,
  Radio,
  Space,
  message,
} from 'antd';
import TextArea from 'antd/lib/input/TextArea';
import UploadImg from '@/components/UploadComponent';
import DaemonMap from '@/components/TencentMap';
import { getCommonCity } from '@/services/commonCityService'
import CustomCascader from '@/components/Cascader';
import { addTakeAwayShop, getTakeAwayShopById, updateTakeAwayShop } from '@/services/takeAwayShopService'

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 },
  },
};

interface Props {
  id?: number,
  submitData: () => void;
  initImgUrl: string;
}

const ShopForm: React.FC<Props> = (props) => {
  const mapRef = useRef<null | any>(null);
  const { id, submitData, initImgUrl } = props;
  const [shopType, setShopType] = useState(1);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [avatar, setAvatar] = useState<string>(initImgUrl);
  const [cityData, setCityData] = useState<any[]>([]);
  const [address, setAddress] = useState('');
  const [areaValue, setAreaValue] = useState<any[]>([]);
  const [lng, setLng] = useState<string>();
  const [lat, setLat] = useState<string>();
  const [coordinate, setCoordinate] = useState();
  const [areaId, setAreaId] = useState<any[]>([]);
  const [form] = Form.useForm();
  const showMapAddress = (addressInfo: any) => {
    const { addressDetail, lngLat } = addressInfo;
    setLng(lngLat.lng);
    setLat(lngLat.lat);
    setAddress(addressDetail);
    setCoordinate(lngLat);
    form.setFieldValue("Coordinate", lngLat);
    form.setFieldValue("Address", addressDetail);
  }

  const getCityData = async () => {
    return getCommonCity().then(result => {
      const { Items } = result;
      setCityData(Items);
    })
  }

  const searchArea = async () => {
    // 创建一个POI搜索实例
    // @ts-ignore
    var placeSearch = new AMap.PlaceSearch({
      map: mapRef.current.amap
    });

    if (address != '') {
      // 清除之前的搜索结果
      placeSearch.clear();
      // 对关键字进行搜索
      // @ts-ignore
      placeSearch.search(address); // 关键字搜索
    }
  }

  const imgChange = (value: string) => {
    setAvatar(value);
    form.setFieldValue("ImgUrl", value);
  }

  const cityChange = (value: any) => {
    setAreaId(value);
    console.log(value);
    form.setFieldValue("areaId", value);
  }

  const getShopById = async () => {
    if (!id) {
      return;
    }

    const { Items } = await getTakeAwayShopById(id, { "@relationships": "LocationInfo" });
    if (Items.length > 0) {
      form.setFieldsValue(Items[0]);
      setAvatar(Items[0].ImgUrl);
      setAddress(Items[0].Address);
      setLat(Items[0].Lat);
      setLng(Items[0].Lng);
      const initAreaId = [Items[0].CityId, Items[0].ProvinceId, Items[0].ZoneId];
      setAreaValue(initAreaId);
      form.setFieldValue("areaId", initAreaId);
      form.setFieldValue("Coordinate", { lng: Items[0].Lng, lat: Items[0].Lat });
    }
    setIsLoading(true);
  }

  const saveShop = async () => {
    const formValue = form.getFieldsValue();
    const addEntity = { ...form.getFieldsValue(), Lng: formValue.Coordinate.lng, Lat: formValue.Coordinate.lat, CityId: formValue.areaId[0], ProvinceId: formValue.areaId[1], ZoneId: formValue.areaId[2] };
    const promise = id ? updateTakeAwayShop({ Id: id, ...addEntity }, { "@relationships": "LocationInfo" })
      : addTakeAwayShop(addEntity, { "@relationships": "LocationInfo" });
    const { StatusCode } = await promise;
    if (StatusCode == 0) {
      message.success("保存成功！");
      submitData();
    }
  }

  useEffect(() => {
    setIsLoading(false);
    getCityData().then(() => {
      form.resetFields();
      if (!id) {
        setAreaValue([]);
        setIsLoading(true);
        return;
      }

      getShopById();
      form.setFieldValue("shopType", 1);
    });
  }, [id]);

  return (
    <Form key={id} form={form} {...formItemLayout} style={{ maxWidth: 600, marginTop: 20 }}>
      <Form.Item label="门店名称" name="Name" rules={[{ required: true, message: '请填写门店名称!' }]}>
        <TextArea />
      </Form.Item>

      <Form.Item
        label="门店logo"
        name="ImgUrl"
        rules={[{ required: true, message: 'Please input!' }]}
      >
        {isLoading ? <UploadImg initialUrl={avatar} callBack={imgChange} /> : null}
      </Form.Item>

      <Form.Item
        label="联系人"
        name="ContactPerson"
        rules={[{ required: true, message: '请填写联系人!' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="门店电话"
        name="TelNumber"
        rules={[{ required: true, message: '请填写联系电话!' }]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="起送金额"
        name="MinPrice"
      >
        <InputNumber />
      </Form.Item>

      <Form.Item
        label="包装费"
        name="PackingPrice"
      >
        <InputNumber />
      </Form.Item>

      <Form.Item label="所属区域" name="areaId" rules={[
        {
          required: true,
        },
      ]}>
        <>
          {isLoading ? <CustomCascader defaultValue={areaValue} options={cityData} change={cityChange} /> : null}
          <Input value={areaId} type='hidden' />
        </>
      </Form.Item>

      <Form.Item label="门店类别" name="ShopType" rules={[{ required: true, }]}>
        <Radio.Group value={shopType}>
          <Radio value={1} > 直营店 </Radio>
          <Radio value={2}> 加盟店 </Radio>
        </Radio.Group>
      </Form.Item>

      <Form.Item
        label="详细地址"
        name="Address"
        rules={[{ required: true, message: '请输入详细地址!' }]}
      >
        <Space.Compact style={{ width: '100%' }}>
          <Input value={address} onChange={(e) => { setAddress(e.target.value) }} />
          <Button type="primary" onClick={searchArea}>搜索</Button>
        </Space.Compact>
      </Form.Item>

      <Form.Item
        label="营业时间"
        name="Description"
        rules={[{ required: true, message: '请填写营业时间!' }]}
      >
        <Input placeholder='示例： 上午10:00 - 下午10:00' />
      </Form.Item>

      <Form.Item
        label="店铺经纬度"
        name="Coordinate"
        rules={[{ required: true, message: '请输入经纬度!' }]}
      >
        <>
          <Input value={coordinate} type='hidden' />
          经度：  <InputNumber value={lng} readOnly />
          <label style={{ marginLeft: "70px" }}>纬度： <InputNumber readOnly value={lat} /></label></>
      </Form.Item>

      <Form.Item
        label="店铺定位"
      >
        {isLoading ? <DaemonMap mapRef={mapRef} initialLat={lat || ""} initialLng={lng || ""} getAddress={showMapAddress} /> : null}
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
        <Button type="primary" htmlType="submit" onClick={saveShop}>
          保存
        </Button>
      </Form.Item>
    </Form>
  )
};

export default ShopForm;
